package com.orange.common.log.aop;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @Description: 日志切面--记录Controller层中所有接口传入的参数
 * 并做属性依赖判断，如果开启则进行记录，如果没有被开启，那么就不创建切面
 */
@Aspect
@Slf4j
@Component
@ConditionalOnProperty(prefix = "orange.log",name = "controllerAspect", havingValue = "true",matchIfMissing = false)
public class LogAspect {

    //定义切点，哪一些类需要生成代理对象
    @Pointcut("execution(* com.orange.*.controller.*Controller.*(..))")
    private void pointCut() {
    }


    //定义环绕通知--记录每一个Controller的接口传入的参数，和传出的参数
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object[] reqArgs = pjp.getArgs();
        String req = new Gson().toJson(reqArgs);
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        String methodName = methodSignature.getDeclaringType().getName() + "." + methodSignature.getName();
        log.info("{},req:{}", methodName, req);
        Long startTime = System.currentTimeMillis();
        Object responseObj = pjp.proceed();
        String resp = new Gson().toJson(responseObj);
        Long endTime = System.currentTimeMillis();
        log.info("{},response:{},costTime:{}", methodName, resp, endTime - startTime);
        return responseObj;
    }

}
